package com.youlu.campus.service.course;

import com.youlu.campus.entity.course.ActivityPopup;
import com.youlu.campus.entity.course.dto.ActivityPopupQueryDTO;
import com.youlu.campus.entity.course.vo.ActivityPopupResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : [dengbo]
 * @className : ActivityPopupService
 * @description : [活动弹窗服务]
 * @createTime : [2022/11/29 11:35]
 */
@Service
@Slf4j
public class ActivityPopupService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public ActivityPopupResultVo findActivityResult(ActivityPopupQueryDTO dto) {
        Date date = new Date();
        Query query = new Query();
        query.addCriteria(Criteria.where("popupType").is(dto.getPopupType()));
        query.addCriteria(Criteria.where("startTime").lte(date));
        query.addCriteria(Criteria.where("endTime").gte(date));
        List<ActivityPopup> list = mongoTemplate.find(query, ActivityPopup.class);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        list = list.stream().filter(item->!item.getDeleted()).sorted(Comparator.comparing(ActivityPopup::getCreatedTime).reversed()).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        ActivityPopup popup = list.get(0);
        ActivityPopupResultVo vo = new ActivityPopupResultVo();
        BeanUtils.copyProperties(popup, vo);
        return vo;
    }

}
